<template>
  <div class="normal-customs" ref="tabpaneContainer">
      <div class="block filter-body">
        <el-input @change="changeFilterData('channel_id')" v-model="filterData.channel_id" class="short-filter-input filter-item" placeholder="输入渠道ID,筛选客户"></el-input>
        <el-pagination  class="filter-item mgl"
          ref="pagination"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 100, 200, 300, 400]"
          :page-size="queryData.page_size"
          layout="sizes, prev, pager, next, jumper, total"
          :total="this.total">
        </el-pagination>
      </div>
      <el-table
        :data="list"
       border
       :min-height="tabHeight"
       :height="tabHeight"
       style="width: 98%">
       <el-table-column
         prop="insert_time"
         label="日期"
         width="200">
       </el-table-column>
       <el-table-column
         prop="channel_name"
         label="渠道"
         width="230">
       </el-table-column>
       <el-table-column
         v-if="type == 0"
         prop="nick_name"
         label="昵称"
         width="200">
       </el-table-column>
       <el-table-column
       :formatter = "formateSources"
         v-if="type == 1"
         prop="source_id"
         label="客户来源"
         width="120">
       </el-table-column>
       <el-table-column label="家长" align="center">
         <el-table-column
           prop="parent_name"
           label="姓名"
           width="220">
         </el-table-column>
         <el-table-column
           prop="mobile_num"
           label="手机"
           width="200">
         </el-table-column>
       </el-table-column>

       <el-table-column
        :formatter = "formateStatus"
         prop="custom_status"
         label="跟进状态"
         width="120">
       </el-table-column>
       <!-- <el-table-column
        :formatter = "formateCustomType"
         prop="custom_type"
         v-if="type == 0"
         label="客户类型"
         width="120">
       </el-table-column> -->
       <el-table-column
        :formatter = "formateProperty"
         prop="custom_property"
         label="客户属性"
         width="98">
       </el-table-column>
       <el-table-column label="地址" v-if="type == 1" align="center">
         <el-table-column
           prop="city"
           label="城市"
           width="100">
         </el-table-column>
         <el-table-column
           prop="district"
           label="区域"
           width="90">
         </el-table-column>
       </el-table-column>
       <el-table-column
         prop="user_name"
         label="营销顾问"
         width="200">
       </el-table-column>
       <el-table-column
        fixed="right"
        label="操作"
        width="110">
        <template scope="scope">
          <el-button @click.native.prevent="view(scope)" type="text" size="small">查看</el-button>
          <el-button @click.native.prevent="editCustom(scope)" type="text" size="small">编辑</el-button>
        </template>
      </el-table-column>
     </el-table>
   </div>
  </div>
</template>

<style lang="scss">
  @import '../scss/index';
  .normal-customs {
    .el-input.short-filter-input {
      width: 160px;
    }

    .filter-body .filter-item {
      float: left;
      .el-input__inner {
        height: 28px;
      }

      &.mgl {
        margin-left: 10px;
      }

      &.el-pagination {
        padding: 0;
      }
    }
  }
</style>

<script>
import Header from 'components/AdminHeader'
import LeftSideBar from 'components/LeftSideBar'
import SelectSite from 'components/SelectSite'
import { Col } from 'element-ui'
import { mapState, mapActions } from 'vuex'
import { Popover, Breadcrumb, BreadcrumbItem,
  Tabs, TabPane, Button,Table,
  TableColumn, Pagination, Form, FormItem, Select, Input, Option } from 'element-ui'
import commonFilter from '../common/customs'
import Config from '../config/common'
import Icon from 'vue-awesome/components/Icon.vue'
import 'vue-awesome/icons/wpexplorer'

export default {
  props: {
    tabHeight: {
      type: String | Number,
      default: 300
    },
    type: {
      type: String | Number,
      default: 1
    }
  },
  data () {
    return {
      customData: [],
      customId: null,
      loading: false,
      filterData: {
        channel_id: null
      },
      isInit: false,
      list: [],
      filters: [],
      currentPage: 1,
      total: 0,
      queryData: {
        'page_index': 1,
        'page_size': 10
      }
      // tabHeight: 200
    }
  },

  watch: {
    dataDictionary (val) {

    },
    loading (val) {
      this.$emit('changeLoading', val)
    }
  },
  methods: {
    onExportSubmit () {
    },
    onExportCancel () {
      this.showExportFilter = false
    },
    handleSizeChange (val) {
      this.queryData['page_size'] = val
      this.page_size = val
      // hack
      this.setSizeInputVal(val)
      console.log(`每页 ${val} 条`)
      this.emptyDatas()
      this.getCustoms()
    },
    changeFilterData () {
      if (this.filterData.channel_id && this.filterData.channel_id.replace(' ', '')) {
        this.emptyList()
        this.getCustoms()
      } else {
        console.debug('no filter data')
        this.emptyDatas()
        this.getCustoms()
      }
    },
    emptyList () {
      this.list = []
    },
    setSizeInputVal (val) {
      const sizeInput = this.$refs.pagination.$el.getElementsByClassName('el-input__inner')[0]
      val = val + ' ' + '条/页'
      sizeInput.value = val
    },
    changeVal (el, val) {
      el.$el.getElementsByClassName('el-input__inner')[0].value = val || '请选择'
    },
    handleCurrentChange (val) {
      this.queryData['page_index'] = val
      console.log(`当前页: ${val}`)
      this.emptyDatas()
      this.getCustoms()
    },
    view ($scope) {
      this.$router.push({ name: 'customsDt', params: { id: $scope.row.id }})
    },
    editCustom ($scope) {
      this.$router.push({ name: 'editCustom', params: { id: $scope.row.id }})
    },
    emptyDatas () {
      this.list = []
      this.filterData = {}
    },
    reverse (object) {
      var NewObj = {}
      var keysArr = Object.keys(object)
      for (var i = keysArr.length - 1; i >= 0; i--) {
        NewObj[keysArr[i]] = object[keysArr[i]]
      }
      return NewObj
    },
    filterPage (value, row) {
      console.log(value, row)
      return row.page_index === value
    },
    removeEmptyValues (dataObj) {
      const freshObject = {}
      for (const key in dataObj) {
        if (dataObj[key]) freshObject[key] = dataObj[key]
      }
      return freshObject
    },
    getCustoms (params) {
      this.loading = true
      const filterData = this.removeEmptyValues(this.filterData)
      const queryData = Object.assign({}, filterData, this.queryData, params || {})
      this.requestCustoms(queryData).then((response) => {
        const resData = response.data
        this.initPageFilters(resData.results)
        if (resData.errcode === 0 && resData.results && resData.results.data) {
          this.list = response.data.results.data
          // this.queryData['page_index'] = resData.results.currentPage
          this.total = resData.results.total
          this.currentPage = resData.results.current_page
          console.log('resData.results', this.currentPage, resData)
        } else {
          console.log('空数据')
        }
        this.loading = false
      }).catch((error) => {
        // console.log(error)
        console.log(error)
        this.loading = false
      })
    },
    initPageFilters (pageData) {
      const totalPage = Math.ceil(pageData['total'] / this.queryData.page_size)
      for (let i = 1; i <= totalPage; i++) {
        this.filters.push({
          value: i,
          text: i
        })
      }
    },
    succesUpload (response, file, fileList) {
      const results = response.results
      console.log('ssswwwww', JSON.stringify({
        file: file,
        tableData: data,
        error: response.errcode !== 0,
        code: response.errcode,
        msg: response.errmsg
      }))
      const all = results.success + results.failed
      const data = [
        {
          'desc': '总条数',
          'value': all + '条'
        },
        {
          'desc': '失败条数',
          'value': results.failed + '条'
        },
        {
          'desc': '成功条数',
          'value': results.success + '条'
        }
      ]
      console.log('results', results)
      this.responseList = this.reverse(Object.assign({},
        this.responseList, {
          [file.name]: {
            file: file,
            tableData: data,
            error: response.errcode !== 0,
            code: response.errcode,
            msg: response.errmsg,
            downloadLink: results.download_link
          }
        }))
    },
    initialize () {
      // const type = this.$route.query.type
      this.loading = true
      // if (this.customId) {
      //   if (type === 'edit') {
      //     this.activeName = 'profile-edit'
      //     this.isEdit = true
      //   } else {
      //     this.activeName = 'profile-detail'
      //   }
      //   this.initCustom(this.customId)
      // } else {
      //   this.activeName = 'profile-info'
      this.getCustoms()
      // }
    },
    ...commonFilter,
    ...mapActions({
      requestCustoms: 'getCustoms',
      getDictionary: 'getDictionary',
      getCustom: 'getCustom',
      saveCustom: 'saveCustom',
      updateMenuIndex: 'updateMenuIndex'
    })
  },
  mounted: function () {
    this.queryData['custom_type'] = this.type
    this.customId = this.$route.params.id
    this.uploadAction = Config.CRM_API_HOST + '/users/' + this.token + '/import'
    this.setSizeInputVal(this.queryData.page_size)
    this.getDictionary()
    if ((!!this.switch_site) === false) {
      this.initialize()
    }
  },

  components: {
    ELHeader: Header,
    LeftSideBar: LeftSideBar,
    [Popover.name]: Popover,
    [Breadcrumb.name]: Breadcrumb,
    [Tabs.name]: Tabs,
    [TabPane.name]: TabPane,
    [BreadcrumbItem.name]: BreadcrumbItem,
    [Button.name]: Button,
    [Table.name]: Table,
    [TableColumn.name]: TableColumn,
    [Pagination.name]: Pagination,
    [Form.name]: Form,
    [Select.name]: Select,
    [Input.name]: Input,
    [Option.name]: Option,
    [FormItem.name]: FormItem,
    SelectSite,
    'el-col': Col,
    'icon': Icon
  },
  computed: {
    ...mapState({
      token: state => state.auth.user.token,
      dataDictionary: state => state.custom.data_dictionary,
      switchSite: state => state.custom.switch_site
    })
  }
}

</script>
